package cn.iocoder.yudao.framework.swagger;

import cn.iocoder.yudao.framework.business.basic.enums.EnumCodable;
import cn.iocoder.yudao.framework.business.basic.enums.EnumValuable;
import cn.iocoder.yudao.framework.common.core.ArrayValuable;
import cn.iocoder.yudao.framework.common.validation.InEnum;
import cn.iocoder.yudao.framework.validation.InEnumCode;
import cn.iocoder.yudao.framework.validation.InEnumValue;
import io.swagger.v3.core.converter.AnnotatedType;
import io.swagger.v3.oas.models.media.Schema;
import org.springdoc.core.customizers.PropertyCustomizer;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.Arrays;

/**
 * <pre>
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 *  自定义枚举类的 Swagger 文档
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * </pre>
 *
 * @link <a href="https://gitee.com/lab1024/smart-admin/blob/master/smart-admin-api-java17-springboot3/sa-base/src/main/java/net/lab1024/sa/base/common/swagger/SchemaEnumPropertyCustomizer.java">SchemaEnumPropertyCustomizer.java</a>
 * @author 1024创新实验室-主任:卓大
 * @author 山野羡民（1032694760@qq.com）
 * @since 2025/04/03
 */
@Component
public class SchemaEnumPropertyCustomizer implements PropertyCustomizer {

    @Override
    public Schema<?> customize(Schema schema, AnnotatedType type) {
        if (type.getCtxAnnotations() == null) {
            return schema;
        }
        StringBuilder builder = new StringBuilder();
        for (Annotation ctxAnnotation : type.getCtxAnnotations()) {
            if (ctxAnnotation.annotationType().equals(InEnum.class)) {
                builder.append(((InEnum) ctxAnnotation).message());
                Class<? extends ArrayValuable<?>> clazz = ((InEnum) ctxAnnotation).value();
                ArrayValuable<?>[] arrayValuables = clazz.getEnumConstants();
                builder.append(Arrays.toString(arrayValuables[0].array()));
            } else if (ctxAnnotation.annotationType().equals(InEnumValue.class)) {
                builder.append(((InEnum) ctxAnnotation).message());
                Class<? extends EnumValuable> clazz = ((InEnumValue) ctxAnnotation).value();
                builder.append(EnumValuable.toString(clazz));
            } else if (ctxAnnotation.annotationType().equals(InEnumCode.class)) {
                builder.append(((InEnumCode) ctxAnnotation).message());
                Class<? extends EnumCodable> clazz = ((InEnumCode) ctxAnnotation).value();
                builder.append(EnumCodable.toString(clazz));
            }
        }
        if (!builder.isEmpty()) {
            schema.setDescription(builder.toString());
        }
        return schema;
    }

}
